//
//  YKAddYKDrugPriceViewController.m
//  YunKang
//
//  Created by leoking870 on 2017/10/4.
//  Copyright © 2017年 leoking870. All rights reserved.
//

#import "YKAddYKDrugPriceViewController.h"
#import "YKClientListHeaderView.h"
#import "YKApproveDetailItem.h"
#import "YKPopupView.h"
#import "YKSelectDrugViewController.h"
#import "YKClientDataModel.h"
#import "YKSelectView.h"
#import "YKInputView.h"
#import "YKClientDrugPriceDetailDetailItem.h"
#import "YKTurnOverViewController.h"
#import "YKTurnOverUserModel.h"
#import "WorkFlowManager.h"

@interface YKAddYKDrugPriceViewController ()
@property (nonatomic, strong)NSString *applyorderode;
@property (nonatomic, strong)NSString *applydate;
@property (nonatomic, strong)NSArray<YKClientDataModel *> *cdList;
@property (nonatomic, strong)YKSelectView* selectClientView;
@property (nonatomic, strong)NSString *businessID;
@end

@implementation YKAddYKDrugPriceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"新增协议价格";
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    if (self.mYKClientDrugPriceDetailModel) {
        self.applyorderode = self.mYKClientDrugPriceDetailModel.APPLYORDERODE;
        self.applydate = self.mYKClientDrugPriceDetailModel.APPLYDATE;
        self.cdList = @[self.mYKClientDrugPriceDetailModel.customerDataMap];
        [self updateView];
    }
    else {
        [self tf_showStateView:kTFViewStateLoading];
        [TFHTTPMANAER POST:@"customerDrugPriceManager/toAddCustomerDrugPriceManager.htm"
                parameters:nil
                   success:^(id responseObject) {
            self.applyorderode = responseObject[@"applyorderode"];
            self.applydate = responseObject[@"applydate"];
            self.cdList = [NSArray yy_modelArrayWithClass:[YKClientDataModel class] json:responseObject[@"cdList"]];
            [self updateView];
            [self tf_showStateView:kTFViewStateNone];
        } failure:^(id responseObject, NSError *error) {
            [self tf_showStateView:kTFViewStateNetError];
        }];
    }
}

- (void)updateView {
    YKInputView* visigNoView = [[YKInputView alloc]initWithTitle:@"申请单号" input:self.applyorderode];
    
    visigNoView.editable = NO;
    [self.view addSubview:visigNoView];
    
    YKInputView* visigDateView = [[YKInputView alloc]initWithTitle:@"申请日期" input:self.applydate];
    visigDateView.editable = NO;
    
    [self.view addSubview:visigDateView];
    YKSelectView* selectClientView = [[YKSelectView alloc]initWithTitle:@"选择客户" row:self.cdList initialText:self.cdList.firstObject];
    [self.view addSubview:selectClientView];
    self.selectClientView = selectClientView;
    [@[visigNoView, visigDateView,selectClientView] mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.width.mas_equalTo(self.view.mas_width);
    }];
    
    [@[visigNoView, visigDateView,selectClientView] mas_alignAlongAxis:MASAxisTypeVertical fixedSpace:@0 leadSpace:8];
    //@[@"序号",@"药品名称",@"药品规格",@"协议价"]
    //@[@1,@4,@2,@2]
    YKClientListHeaderView *listHeaderView = [[YKClientListHeaderView alloc]initWithTitles:@[@"药品信息",@"类型",@"协议价"] weights:@[@3,@1,@1] spaceing:0 leading:3 trailing:3];
    listHeaderView.textFont = [UIFont systemFontOfSize:16];
    
    [self.view addSubview:listHeaderView];
    [listHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(selectClientView.mas_bottom).offset(8);
    }];
    
    UIButton* addButton = [[UIButton alloc]init];
    [self.view addSubview:addButton];
    UIButton *saveButton = [[UIButton alloc]init];
    [self.view addSubview:saveButton];
    UIButton *cancleButton = [[UIButton alloc]init];
    [self.view addSubview:cancleButton];
    UIButton *submitButton = [[UIButton alloc]init];
    [self.view addSubview:submitButton];
    [addButton setTitle:@"添加" forState:UIControlStateNormal];
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    [submitButton setTitle:@"提交审批" forState:UIControlStateNormal];
    [addButton setBackgroundColor:TFSTYLE(buttonEnableBackgroundColor)];
    [saveButton setBackgroundColor:TFSTYLE(buttonEnableBackgroundColor)];
    [cancleButton setBackgroundColor:TFSTYLE(buttonEnableBackgroundColor)];
    [submitButton setBackgroundColor:TFSTYLE(buttonEnableBackgroundColor)];
    
    [addButton setTitleColor:TFSTYLE(buttonEnableTitleColor) forState:UIControlStateNormal];
    [saveButton setTitleColor:TFSTYLE(buttonEnableTitleColor) forState:UIControlStateNormal];
    [cancleButton setTitleColor:TFSTYLE(buttonEnableTitleColor) forState:UIControlStateNormal];
    [submitButton setTitleColor:TFSTYLE(buttonEnableTitleColor) forState:UIControlStateNormal];
    addButton.titleLabel.font = [UIFont systemFontOfSize:14];
    saveButton.titleLabel.font = [UIFont systemFontOfSize:14];
    cancleButton.titleLabel.font = [UIFont systemFontOfSize:14];
    submitButton.titleLabel.font = [UIFont systemFontOfSize:14];
    
    [submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    [addButton addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    [saveButton addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    [cancleButton addTarget:self action:@selector(cancle:) forControlEvents:UIControlEventTouchUpInside];
    [@[addButton,saveButton,cancleButton,submitButton] mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:1 leadSpacing:0 tailSpacing:0];
    [@[addButton,saveButton,cancleButton,submitButton] mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(listHeaderView.mas_bottom);
        make.bottom.equalTo(addButton.mas_top);
    }];
    
    if (self.mYKClientDrugPriceDetailModel) {
        TFTableViewSection *section = [TFTableViewSection section];
        section.headerHeight = .1f;
        section.footerHeight = .1f;
        for (YKClientDrugPriceDetailDetailModel *model in self.mYKClientDrugPriceDetailModel.customerDrugPriceDetail) {
            YKClientDrugPriceDetailDetailItem *item = [YKClientDrugPriceDetailDetailItem itemWithModel:model];
            //item.cellHeight = 95;
            item.titleForDelete = @"删除";
            item.deletionHandler = ^(__kindof TFTableViewItem *item, NSIndexPath *indexPath) {
                [section removeItem:item];
                [section reloadSectionWithAnimation:UITableViewRowAnimationFade];
            };
            item.editingStyle = UITableViewCellEditingStyleDelete;
            [section addItem:item];
        }
        [self.tableViewManager addSection:section];
    }
}

- (void)submit:(id)sender {
    if (self.businessID){
        [WorkFlowManager submitToApproveWithBusinessID:self.businessID
                                    fromViewController:self];
    }
    else {
        [self saveDrugPriceWithCompletion:^(NSError *error, NSString *ID) {
            if (!error){
                self.businessID = ID;
                [WorkFlowManager submitToApproveWithBusinessID:self.businessID
                                            fromViewController:self];
            }
            else {
                [self showHint:error.localizedFailureReason];
            }
        }];
    }
    
}

//
//- (void)submitToApprove:(NSString*)ID {
//    NSString *cid = self.selectClientView.selectedRow.id_p;
//
//    NSMutableArray *selectedDrugs = [NSMutableArray array];
//    for (TFTableViewSection *sectioin in self.tableViewManager.sections) {
//        for (YKClientDrugPriceDetailDetailItem* item in sectioin.items) {
//            [selectedDrugs addObject:item.model];
//        }
//    }
//
//    NSString *list = [selectedDrugs yy_modelToJSONString];
//    list = [list stringByReplacingOccurrencesOfString:@"DRUGNAME" withString:@"drugname"];
//    list = [list stringByReplacingOccurrencesOfString:@"DRUGPRICE" withString:@"drugprice"];
//    list = [list stringByReplacingOccurrencesOfString:@"DRUGCODE" withString:@"drugcode"];
//
//    [TFHTTPMANAER POST:@"customerDrugPriceManager/doAddCustomerDrugPriceManager.htm" parameters:@{@"list":list?:@"", @"applyorderode":self.applyorderode, @"applydate":self.applydate, @"cid":cid,@"subState":@"1"} HUD:@"提交审批中..." success:^(id responseObject) {
//
//        YKTurnOverViewController *vc = [YKTurnOverViewController new];
//        vc.m_id = ID;
//        vc.type = YKTurnOverTypeApprove;
//        NSArray *user = [NSArray yy_modelArrayWithClass:[YKTurnOverUserModel class] json:[responseObject valueForKeyPath:@"userList.mapSel"]];
//        vc.users = user;
//        vc.nextTask = [NSArray yy_modelArrayWithClass:[YKTurnOverUserTaskModel class] json:[responseObject valueForKeyPath:@"nextTask"]].firstObject;
//
//        vc.m_id = responseObject[@"businessId"];
//        vc.submitBlock = ^(NSString *text, NSString *businessId, NSString *nextId) {
//            [TFHTTPMANAER POST:@"workExamine/completeWorkExamine.htm" parameters:@{@"mark":text,@"businessId":businessId,@"nextId":nextId} HUD:@"转审中..." success:^(id responseObject) {
//                [self showHint:@"提交审批成功"];
//                [self.navigationController popViewControllerAnimated:YES];
//            } failure:^(id responseObject, NSError *error) {
//                [self showHint:error.localizedFailureReason];
//            }];
//        };
//
//        [YKPopupView showPopupViewWithViewController:vc];
//
//    } failure:^(id responseObject, NSError *error) {
//        [self showHint:error.localizedFailureReason];
//    }];
//}

- (void)add:(id)sender {
    YKSelectDrugViewController *vc = [YKSelectDrugViewController new];
    vc.selectDrugComplete = ^(NSArray<YKSelectDrugModel *> *drugs) {
        TFTableViewSection *section = [TFTableViewSection section];
        section.headerHeight = .1f;
        section.footerHeight = .1f;
        for (YKSelectDrugModel *model in drugs) {
            BOOL exist = NO;
            for (TFTableViewSection *sectioin in self.tableViewManager.sections) {
                for (YKClientDrugPriceDetailDetailItem* item in sectioin.items) {
                    if ([item.model.ID isEqualToString:model.ID]) {
                        exist = YES;
                    }
                }
            }
            if (exist) {
                continue;
            }
            YKClientDrugPriceDetailDetailModel *drugmodel = [[YKClientDrugPriceDetailDetailModel alloc]init];
//            drugmodel.ID = model.ID;
            drugmodel.PID = model.PID;
            drugmodel.DRUGNAME = model.CINV_NAME;
            drugmodel.DRUGCODE = model.CINVMNEM_CODE;
            drugmodel.DRUGPRICE = model.DRUGPRICE;
            drugmodel.CPACKINGTYPE = model.CPACKINGTYPE;
            drugmodel.FACE_PIC1 = model.FACE_PIC1;
            drugmodel.WHOLE_PRICE = model.WHOLE_PRICE;
            drugmodel.CENTERPRISE = model.CENTERPRISE;
            drugmodel.LOWEST_PRICE = model.LOWEST_PRICE;
            drugmodel.GIVE_INTEGRAL = model.GIVE_INTEGRAL;
            drugmodel.PERFORMANCE_POINTS = model.PERFORMANCE_POINTS;
            YKClientDrugPriceDetailDetailItem *item = [YKClientDrugPriceDetailDetailItem itemWithModel:drugmodel];
            //item.cellHeight = 95;
            item.titleForDelete = @"删除";
            item.deletionHandler = ^(__kindof TFTableViewItem *item, NSIndexPath *indexPath) {
                [section removeItem:item];
                [section reloadSectionWithAnimation:UITableViewRowAnimationFade];
            };
            item.editingStyle = UITableViewCellEditingStyleDelete;
            [section addItem:item];
        }
        [self.tableViewManager addSection:section];
        [self.tableView reloadData];
    };
    NSMutableArray *selectedDrugs = [NSMutableArray array];
    for (TFTableViewSection *sectioin in self.tableViewManager.sections) {
        for (YKClientDrugPriceDetailDetailItem* item in sectioin.items) {
            [selectedDrugs addObject:item.model];
        }
    }
    vc.selectedDrugs = selectedDrugs;
    [YKPopupView showPopupViewWithViewController:vc height:self.view.tf_height - 150];
}


- (void)saveDrugPriceWithCompletion:(void(^)(NSError* error, NSString *ID))completion {
    NSString *cid = self.selectClientView.selectedRow.id_p;

    NSMutableArray *selectedDrugs = [NSMutableArray array];
    for (TFTableViewSection *sectioin in self.tableViewManager.sections) {
        for (YKClientDrugPriceDetailDetailItem* item in sectioin.items) {
            [selectedDrugs addObject:item.model];
        }
    }

    NSString *list = [selectedDrugs yy_modelToJSONString];
    list = [list stringByReplacingOccurrencesOfString:@"DRUGNAME" withString:@"drugname"];
    list = [list stringByReplacingOccurrencesOfString:@"DRUGPRICE" withString:@"drugprice"];
    list = [list stringByReplacingOccurrencesOfString:@"DRUGCODE" withString:@"drugcode"];
    list = [list stringByReplacingOccurrencesOfString:@"GIVE_INTEGRAL" withString:@"give_integral"];

    [TFHTTPMANAER POST:@"customerDrugPriceManager/doAddCustomerDrugPriceManager.htm" parameters:@{@"list":list?:@"", @"applyorderode":self.applyorderode, @"applydate":self.applydate, @"cid":cid,@"subState":@"0"} HUD:@"添加中..." success:^(id responseObject) {
//        [self showHint:@"添加成功"];
//        [self.navigationController popViewControllerAnimated:YES];
        if (completion){
            completion(nil, responseObject[@"businessId"]);
        }
    } failure:^(id responseObject, NSError *error) {
//        [self showHint:@"添加失败, 请点击重试"];
        if (completion){
            completion(error, nil);
        }
    }];
}

- (void)save:(id)sender {
    NSString *cid = self.selectClientView.selectedRow.id_p;
    
    NSMutableArray *selectedDrugs = [NSMutableArray array];
    for (TFTableViewSection *sectioin in self.tableViewManager.sections) {
        for (YKClientDrugPriceDetailDetailItem* item in sectioin.items) {
            [selectedDrugs addObject:item.model];
        }
    }
    
    NSString *list = [selectedDrugs yy_modelToJSONString];
    list = [list stringByReplacingOccurrencesOfString:@"DRUGNAME" withString:@"drugname"];
    list = [list stringByReplacingOccurrencesOfString:@"DRUGPRICE" withString:@"drugprice"];
    list = [list stringByReplacingOccurrencesOfString:@"DRUGCODE" withString:@"drugcode"];
    list = [list stringByReplacingOccurrencesOfString:@"GIVE_INTEGRAL" withString:@"give_integral"];
    if (self.mYKClientDrugPriceDetailModel)
    {
        [TFHTTPMANAER POST:@"customerDrugPriceManager/edtCustomerDrugPriceManager.htm" parameters:@{@"id":self.mYKClientDrugPriceDetailModel.customerDrugPrice.ID,@"list":list?:@"", @"applyorderode":self.applyorderode, @"applydate":self.applydate, @"cid":cid} HUD:@"添加中..." success:^(id responseObject) {
            [self showHint:@"编辑成功"];
            [self.navigationController popViewControllerAnimated:YES];
        } failure:^(id responseObject, NSError *error) {
            [self showHint:@"编辑失败, 请点击重试"];
        }];
    }
    else {
        [self saveDrugPriceWithCompletion:^(NSError *error, NSString *ID) {
            if (!error){
                [self showHint:@"添加成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else {
                [self showHint:error.localizedFailureReason];
            }
        }];
//        [TFHTTPMANAER POST:@"customerDrugPriceManager/doAddCustomerDrugPriceManager.htm" parameters:@{@"list":list?:@"", @"applyorderode":self.applyorderode, @"applydate":self.applydate, @"cid":cid,@"subState":@"0"} HUD:@"添加中..." success:^(id responseObject) {
//            [self showHint:@"添加成功"];
//            [self.navigationController popViewControllerAnimated:YES];
//        } failure:^(id responseObject, NSError *error) {
//            [self showHint:@"添加失败, 请点击重试"];
//        }];
    }
    
    
}
- (void)cancle:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
@end
